package br.com.affero.servlet;

import br.com.affero.model.bean.Documento;
import br.com.affero.model.bo.DocumentoBO;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {
    
    private DocumentoBO documentoBO = DocumentoBO.getInstance();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Integer codigoDocumento = Integer.parseInt(request.getParameter("codigoDocumento"));
        Documento doc = documentoBO.obterDocumento(codigoDocumento);
        
        ServletOutputStream output = response.getOutputStream();
        ByteArrayInputStream bis = new ByteArrayInputStream(doc.getDocumento());
        
        response.reset();
        response.setContentType("octet-stream");
        response.setHeader("Content-disposition","attachment; filename=" +doc.getNomeDocumento());
        
        byte[] buf = new byte[1024];
        int len;
        while ((len = bis.read(buf)) > 0){
            output.write(buf, 0, len);
        }
        
        bis.close();
        response.getOutputStream().flush();
    }
    

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
